<template>
  <div class="payment-config-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>支付配置管理</h1>
      <p>管理微信支付的配置参数</p>
    </div>

    <!-- 配置列表 -->
    <div class="config-section">
      <el-card>
        <div class="card-header">
          <h3>配置列表</h3>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            添加配置
          </el-button>
        </div>

        <el-table
          :data="configs"
          v-loading="loading"
          stripe
          style="width: 100%"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="config_name" label="配置名称" width="150" />
          <el-table-column prop="app_id" label="应用ID" width="200" />
          <el-table-column prop="mch_id" label="商户号" width="150" />
          <el-table-column label="环境" width="100">
            <template #default="{ row }">
              <el-tag :type="row.is_sandbox ? 'warning' : 'success'">
                {{ row.is_sandbox ? '沙箱' : '生产' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.is_active ? 'success' : 'danger'">
                {{ row.is_active ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="180" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="editConfig(row)">
                编辑
              </el-button>
              <el-button 
                :type="row.is_active ? 'warning' : 'success'" 
                size="small" 
                @click="toggleActive(row)"
              >
                {{ row.is_active ? '禁用' : '启用' }}
              </el-button>
              <el-button type="danger" size="small" @click="deleteConfig(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 添加/编辑配置对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑配置' : '添加配置'"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="配置名称" prop="config_name">
          <el-input v-model="formData.config_name" placeholder="请输入配置名称" />
        </el-form-item>

        <el-form-item label="应用ID" prop="app_id">
          <el-input v-model="formData.app_id" placeholder="请输入微信应用ID" />
        </el-form-item>

        <el-form-item label="商户号" prop="mch_id">
          <el-input v-model="formData.mch_id" placeholder="请输入微信商户号" />
        </el-form-item>

        <el-form-item label="API密钥" prop="api_key">
          <el-input 
            v-model="formData.api_key" 
            type="password" 
            placeholder="请输入API密钥"
            show-password 
          />
        </el-form-item>

        <el-form-item label="API证书" prop="api_cert">
          <el-input 
            v-model="formData.api_cert" 
            type="textarea" 
            :rows="3"
            placeholder="请输入API证书内容"
          />
        </el-form-item>

        <el-form-item label="证书私钥" prop="api_key_cert">
          <el-input 
            v-model="formData.api_key_cert" 
            type="textarea" 
            :rows="3"
            placeholder="请输入证书私钥内容"
          />
        </el-form-item>

        <el-form-item label="通知地址" prop="notify_url">
          <el-input v-model="formData.notify_url" placeholder="请输入支付通知地址" />
        </el-form-item>

        <el-form-item label="环境设置">
          <el-switch
            v-model="formData.is_sandbox"
            active-text="沙箱环境"
            inactive-text="生产环境"
          />
        </el-form-item>

        <el-form-item label="启用状态">
          <el-switch
            v-model="formData.is_active"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>

        <el-form-item label="描述">
          <el-input 
            v-model="formData.description" 
            type="textarea" 
            :rows="2"
            placeholder="请输入配置描述"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            {{ isEdit ? '更新' : '添加' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getPaymentConfigs, createPaymentConfig, updatePaymentConfig, deletePaymentConfig } from '@/api/payment'

export default {
  name: 'PaymentConfig',
  components: {
    Plus
  },
  setup() {
    const loading = ref(false)
    const submitting = ref(false)
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const configs = ref([])
    const formRef = ref()

    const formData = reactive({
      config_name: '',
      app_id: '',
      mch_id: '',
      api_key: '',
      api_cert: '',
      api_key_cert: '',
      notify_url: '',
      is_sandbox: false,
      is_active: true,
      description: ''
    })

    const formRules = {
      config_name: [
        { required: true, message: '请输入配置名称', trigger: 'blur' }
      ],
      app_id: [
        { required: true, message: '请输入应用ID', trigger: 'blur' }
      ],
      mch_id: [
        { required: true, message: '请输入商户号', trigger: 'blur' }
      ],
      api_key: [
        { required: true, message: '请输入API密钥', trigger: 'blur' }
      ],
      notify_url: [
        { required: true, message: '请输入通知地址', trigger: 'blur' },
        { type: 'url', message: '请输入有效的URL地址', trigger: 'blur' }
      ]
    }

    // 获取配置列表
    const fetchConfigs = async () => {
      try {
        loading.value = true
        const response = await getPaymentConfigs()
        configs.value = response.data.configs || []
      } catch (error) {
        ElMessage.error('获取配置列表失败')
      } finally {
        loading.value = false
      }
    }

    // 显示添加对话框
    const showAddDialog = () => {
      isEdit.value = false
      dialogVisible.value = true
      resetForm()
    }

    // 编辑配置
    const editConfig = (config) => {
      isEdit.value = true
      dialogVisible.value = true
      
      // 填充表单数据
      Object.keys(formData).forEach(key => {
        formData[key] = config[key] || ''
      })
      formData.currentId = config.id
    }

    // 重置表单
    const resetForm = () => {
      if (formRef.value) {
        formRef.value.resetFields()
      }
      Object.keys(formData).forEach(key => {
        if (key === 'is_active') {
          formData[key] = true
        } else if (key === 'is_sandbox') {
          formData[key] = false
        } else {
          formData[key] = ''
        }
      })
    }

    // 提交表单
    const submitForm = async () => {
      if (!formRef.value) return

      try {
        await formRef.value.validate()
        submitting.value = true

        const data = { ...formData }
        delete data.currentId

        if (isEdit.value) {
          await updatePaymentConfig(formData.currentId, data)
          ElMessage.success('配置更新成功')
        } else {
          await createPaymentConfig(data)
          ElMessage.success('配置添加成功')
        }

        dialogVisible.value = false
        fetchConfigs()
      } catch (error) {
        if (error.message) {
          ElMessage.error(error.message)
        }
      } finally {
        submitting.value = false
      }
    }

    // 切换启用状态
    const toggleActive = async (config) => {
      try {
        await updatePaymentConfig(config.id, {
          ...config,
          is_active: !config.is_active
        })
        
        config.is_active = !config.is_active
        ElMessage.success(`配置已${config.is_active ? '启用' : '禁用'}`)
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }

    // 删除配置
    const deleteConfig = async (config) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除配置 "${config.config_name}" 吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        await deletePaymentConfig(config.id)
        ElMessage.success('配置删除成功')
        fetchConfigs()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    onMounted(() => {
      fetchConfigs()
    })

    return {
      loading,
      submitting,
      dialogVisible,
      isEdit,
      configs,
      formRef,
      formData,
      formRules,
      fetchConfigs,
      showAddDialog,
      editConfig,
      resetForm,
      submitForm,
      toggleActive,
      deleteConfig
    }
  }
}
</script>

<style scoped>
.payment-config-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 5px 0;
  color: var(--text-primary);
}

.page-header p {
  margin: 0;
  color: var(--text-secondary);
}

.config-section {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header h3 {
  margin: 0;
  color: var(--text-primary);
}

.dialog-footer {
  text-align: right;
}
</style> 